import { ref, onMounted, onUnmounted, watch } from "vue";
import { reqHome, reqBalanceLog } from "@/api/index";
import { useUserStore, useSelectOptionsStore } from "@/store/index";
import { isoToDate, dateTransform } from "@/utils/index";
import { storeToRefs } from "pinia";

const isoToDateStr = (dateStr) => {
  return dateTransform(isoToDate(dateStr));
};

export const useHome = () => {
  const homeLoading = ref(false);
  const cardInfoList = ref([]);
  const userStore = useUserStore();
  const selectOptionsStore = useSelectOptionsStore();
  const initData = async () => {
    homeLoading.value = true;
    try {
      clog("reqHome参数:", userStore.user_id);
      const res = await reqHome(userStore.user_id);
      clog("首页卡片列表：", res);
      homeLoading.value = false;
      cardInfoList.value = res.data.map((item) => ({
        currency: item.currency,
        account_balance: (
          parseFloat(item.amount) +
          parseFloat(item.freeze_amount) +
          parseFloat(item.risk_margin)
        ).toFixed(2),
        freeze_balance: item.freeze_amount,
        risk_insurance: item.risk_margin,
        available_balance: item.amount,
      }));
      selectOptionsStore.setCurrencyList(res.data);
    } catch (err) {
      clog("initData error:", err);
      homeLoading.value = false;
    }
  };
  initData();

  return {
    cardInfoList,
  };
};

export const useCardSlide = (cardInfoList) => {
  let leftArrowVisbile = ref(false); // 左箭头是否可见
  let rightArrowVisbile = ref(false); // 右箭头是否可见
  const cardPosition = ref(0);
  let index_left_most = 1; // 左边界的第一个盒子的标号
  const box_width = 24; // 单位vw
  const box_view_num = 3; // 容器内可见的盒子数量
  const total_box_num = cardInfoList.value.length; // 总的盒子数量
  const prevCard = () => {
    index_left_most--;
    const box_content_postion = (1 - index_left_most) * box_width;
    cardPosition.value = box_content_postion;
    checkAndToggleArrowVisible();
  };
  const nextCard = () => {
    index_left_most++;
    const box_content_postion = (1 - index_left_most) * box_width;
    cardPosition.value = box_content_postion;
    checkAndToggleArrowVisible();
  };
  const checkAndToggleArrowVisible = () => {
    // 盒子的数量不足以移动
    if (total_box_num <= box_view_num) {
      leftArrowVisbile.value = false;
      rightArrowVisbile.value = false;
      return;
    }
    // 左箭头边界判断
    if (index_left_most > 1 && index_left_most <= box_view_num) {
      leftArrowVisbile.value = true;
    } else {
      leftArrowVisbile.value = false;
    }
    // 右箭头边界判断
    if (index_left_most >= 1 && index_left_most < box_view_num) {
      rightArrowVisbile.value = true;
    } else {
      rightArrowVisbile.value = false;
    }
  };
  checkAndToggleArrowVisible();
  return {
    leftArrowVisbile,
    rightArrowVisbile,
    cardPosition,
    prevCard,
    nextCard,
  };
};

let chart = null;
export const useEcharts = (chartsContainer) => {
  const currencies = ref([]);
  const currentCurrency = ref("");
  const userStore = useUserStore();
  const selectOptionsStore = useSelectOptionsStore();
  const handleChartResize = () => {
    chart.resize();
  };
  onMounted(() => {
    if (chart) {
      return;
    }
    clog("useEcharts mounted", chart);
    if (!chartsContainer.value) {
      return;
    }

    const initChartData = async (Pcu, Pcurrency) => {
      try {
        if (Pcu) {
          currencies.value = Pcu;
          currentCurrency.value = currencies.value[0].value;
        } else if (Pcurrency) {
          currentCurrency.value = Pcurrency;
        }

        const res = await reqBalanceLog({
          user_id: userStore.user_id,
          currency: currentCurrency.value,
        });
        if (!chartsContainer.value) {
          return;
        }
        const xAxisData = res.data.map((item) => isoToDateStr(item.created_at));
        const seriesData = res.data.map((item) => item.last_amount);
        clog("chartsContainer:", chartsContainer.value);
        chart = echarts.init(chartsContainer.value);
        // const seriesData = generateSeriesData();
        clog("echarts数据：", seriesData);
        const option = {
          xAxis: {
            data: xAxisData,
            axisTick: {
              show: false,
            },
          },
          yAxis: {},
          series: [
            {
              name: "資金",
              type: "line",
              data: seriesData,
              lineStyle: {
                color: "#0098FA",
              },
              itemStyle: {
                opacity: 0,
              },
              areaStyle: {
                normal: {
                  color: new echarts.graphic.LinearGradient(
                    0,
                    0,
                    0,
                    1, // 渐变方向参数，从上(0)到下(1)
                    [
                      { offset: 0, color: "rgba(0, 152, 250, 0.2)" }, // 0% 处的颜色
                      { offset: 1, color: "rgba(0, 152, 250, 0)" }, // 100% 处的颜色
                    ]
                  ),
                },
              },
            },
          ],
          grid: {
            left: "0", // 距离左边边缘的距离
            right: "0", // 距离右边边缘的距离
            top: "5%", // 距离上边边缘的距离
            bottom: "0", // 距离下边边缘的距离
            containLabel: true, // 包含坐标轴的标签在内
          },
        };
        chart.setOption(option);

        window.addEventListener("resize", handleChartResize);
      } catch (err) {
        clog("initChartData error:", err);
      }
    };
    if (selectOptionsStore.currencyList.length > 0) {
      initChartData(selectOptionsStore.currencyList);
    } else {
      watch(
        () => selectOptionsStore.currencyList,
        (newVal, oldVal) => {
          clog("useEcharts watch", newVal, oldVal, newVal === oldVal);
          initChartData(newVal);
        }
      );
    }
    // 监听currentCurrency的变化
    watch(currentCurrency, (newVal) => {
      if (newVal) {
        console.log("currentCurrency:", newVal);
        initChartData(null, newVal);
      }
    });
  });
  // 卸载的时候移除resize事件监听
  onUnmounted(() => {
    window.removeEventListener("resize", handleChartResize);
    chart = null;
  });
  return {
    currencies,
    currentCurrency,
  };
};
